package com.wechat.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wechat.admin.common.CommonConstants;
import com.wechat.admin.exception.BusinessException;
import com.wechat.admin.exception.ErrorCode;
import com.wechat.admin.exception.ThrowUtils;
import com.wechat.admin.mapper.UserMapper;
import com.wechat.admin.mapper.WeUserGroupMapper;
import com.wechat.admin.model.dto.UserInfoDto;
import com.wechat.admin.model.dto.WeDeviceDto;
import com.wechat.admin.model.entity.User;
import com.wechat.admin.model.entity.UserGroupLink;
import com.wechat.admin.model.entity.WeUserGroup;
import com.wechat.admin.model.request.AddUserToGroupRequest;
import com.wechat.admin.model.request.GetUserAndDeviceInfoRequest;
import com.wechat.admin.model.request.UserGroupAddRequest;
import com.wechat.admin.model.vo.UserAndDeviceVo;
import com.wechat.admin.model.vo.UserLoginInfoVo;
import com.wechat.admin.service.AssembleService;
import com.wechat.admin.service.ConverterService;
import com.wechat.admin.service.WeUserGroupService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author dell
 * @description 针对表【we_user_group】的数据库操作Service实现
 * @createDate 2024-12-15 10:22:51
 */
@Service
public class WeUserGroupServiceImpl extends ServiceImpl<WeUserGroupMapper, WeUserGroup>
        implements WeUserGroupService {

    @Resource
    UserServiceImpl userService;

    @Resource
    UserGroupLinkServiceImpl userGroupLinkService;

    @Resource
    WeDeviceServiceImpl weDeviceService;

    @Resource
    private AssembleService assembleService;
    @Autowired
    private UserMapper userMapper;

    @Resource
    private ConverterService converterService;
    @Autowired
    private WeUserGroupMapper weUserGroupMapper;


    @Override
    public Boolean createUserGroup(UserGroupAddRequest userGroupAddRequest) {
        ThrowUtils.throwIf(userGroupAddRequest == null, ErrorCode.PARAMS_ERROR);
        String groupName = userGroupAddRequest.getGroupName();
        Integer groupId = userGroupAddRequest.getGroupId();
        Long userId = userGroupAddRequest.getUserId();

        WeUserGroup weUserGroup = this.getBaseMapper().selectById(groupId);
        if (weUserGroup != null) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "分组已存在,请联系管理员添加用户");
        }

        WeUserGroup group = new WeUserGroup();
        group.setGroupName(groupName);
        group.setId(groupId);
        group.setCreateId(userId);
        boolean saved = this.save(group);

        if (!saved) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "创建分组失败");
        }
        return true;
    }

    @Override
    public Boolean addUserToGroup(AddUserToGroupRequest addUserToGroupRequest) {
        String userName = addUserToGroupRequest.getUserName();
        Integer groupId = addUserToGroupRequest.getGroupId();

        QueryWrapper<WeUserGroup> userGroupQueryWrapper = new QueryWrapper<>();
        userGroupQueryWrapper.eq("id", groupId);
        WeUserGroup weUserGroup = weUserGroupMapper.selectOne(userGroupQueryWrapper);
        if (weUserGroup == null){
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR,"未查询到分组信息,请先创建分组");
        }

        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("useraccount", userName);
        User user = userService.getBaseMapper().selectOne(queryWrapper);
        if (user == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "未查询到被添加用户信息");
        }

        // 避免重复添加
        Long id = user.getId();
        QueryWrapper<UserGroupLink> userGroupLinkQueryWrapper = new QueryWrapper<>();
        userGroupLinkQueryWrapper.eq("userid", id);
        userGroupLinkQueryWrapper.eq("groupid", groupId);
        Long count = userGroupLinkService.getBaseMapper().selectCount(userGroupLinkQueryWrapper);
        if (count > 0) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "用户已存在此组,请勿重复添加");
        }

        // 更改此用户信息表中的user_group字段
        user.setUserGroup(groupId);
        userService.updateById(user);

        // 保存用户分组关联表
        UserGroupLink userGroupLink = new UserGroupLink();
        userGroupLink.setUserRole(user.getUserRole());
        userGroupLink.setGroupId(groupId);
        userGroupLink.setUserid(user.getId());
        boolean saved = userGroupLinkService.save(userGroupLink);
        if (!saved) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "添加成员失败");
        }
        return true;
    }

    @Override
    public UserAndDeviceVo getUserAndDevice(GetUserAndDeviceInfoRequest getUserAndDeviceInfoRequest) {
        UserLoginInfoVo currentLoginUser = userService.getCurrentLoginUser();
        String userRole = currentLoginUser.getUserRole();
        Long total = null;
        List<UserInfoDto> userList = null;
        // 2、分页查询用户的信息
        int pageSize = getUserAndDeviceInfoRequest.getPageSize();
        int current = getUserAndDeviceInfoRequest.getCurrent();
        int offset = (current - 1) * pageSize;
        // 如果是管理员 不根据组进行筛选 默认看所有用户信息
        if (CommonConstants.ADMIN.equals(userRole)){
            userList = userService.findAllUser(pageSize, offset);
            total = userMapper.countUsers();
        }else{
            // 1、普通用户此组下面有多少用户 用户&组 关联表 代表总条数信息
            Integer groupId = getUserAndDeviceInfoRequest.getGroupId();
            userList =  userService.findUsersByGroupId(groupId, pageSize, offset);
            total = userMapper.countUsersByGroupId(groupId);
        }
        // 3、提取用户的id信息
        List<Long> userIdlist = userList.stream().map((UserInfoDto::getId)).collect(Collectors.toList());
        // 4、从用户&设备关联表中查userId关联的设备信息
        Map<Long, List<WeDeviceDto>> deviceListByUserIds = weDeviceService.getDeviceListByUserIds(userIdlist);
        // 5. 组装返回数据
        List<UserAndDeviceVo.UserDeviceInfo> records = assembleService.assembleInfoAndData(userList, deviceListByUserIds);

        // 6. 封装分页数据
        UserAndDeviceVo result = new UserAndDeviceVo();
        result.setTotal(total);
        result.setCurrentPage(current);
        result.setPageSize(pageSize);
        result.setRecords(records);
        return result;
    }
}



